package com.otaku.helper;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.awt.image.RenderedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.imageio.ImageIO;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.log4j.Logger;


import com.google.gson.Gson;
import com.otaku.crawler.bean.BaiduBean;
import com.otaku.crawler.bean.Location;
import com.otaku.crawler.util.EmailHelper;

public final class BaiduLocationHelper {
	private static Logger log = Logger.getRootLogger();
	private static final String AK = "0686f68c9197a3451dcb311cfa284140";
	private static final String prefix = "http://api.map.baidu.com/geocoder/v2/?output=json&ak="+AK;
	private static Gson gs = new Gson();
	private static ClientConnectionManager cm;
	static{
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(
		        new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

		cm = new PoolingClientConnectionManager(schemeRegistry);
	}
	
	/**
	 * 
	 * @param city
	 * @param key
	 * @return null means no location info found by baidu
	 */
	public static Location getLocation(String city,String key){
		if(key.startsWith("地址：")) key=key.substring(3);
		if(key.contains(" ")) key=key.replaceAll(" ", "");
		String url = prefix+"&address="+key+((city==null)?"":("&city="+city));
		try {
			HttpClient client = new DefaultHttpClient(cm);
			
			log.warn("url:"+url);
			HttpGet get = new HttpGet(url);
			get.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
			
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			
			if(entity!=null){
				return gs.fromJson(getJson(entity.getContent()), BaiduBean.class).getResult().getLocation();
			}
			return null;
		} catch (Exception e) {
			log.error("getLocation caught exception", e);
			EmailHelper.sendMsg("getLocation caught exception with url:\n"+url, e);
			return null;
		} 
	}

	private static String getJson(InputStream is) throws IOException {
		StringBuffer sb = new StringBuffer();
		BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		String s = "";
		while((s=br.readLine())!=null)
			sb.append(s);
		
		br.close();
		return sb.toString();
	}
	
	public static void main(String[] args){
//		Location l = getLocation(null, "上海影城");
//		System.out.println(l.getLat()+","+l.getLng());
		
		
//		try {
//			Image img = ImageIO.read(new File("C:\\Users\\zzd\\Desktop\\a.jpg"));
//			Graphics2D g = (Graphics2D) img.getGraphics();
//			g.setFont(new Font(null, Font.BOLD, 16));
//			g.setColor(Color.BLACK);
//			g.drawString("hello " , 37, 20);
//			g.dispose();
//			FileOutputStream os = new FileOutputStream("C:\\Users\\zzd\\Desktop\\b.jpg");
//			ImageIO.write((RenderedImage) img, "JPG", os);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}
	
	private BaiduLocationHelper(){}
}
